from django.db import models
from django.utils import timezone

class WechatUser(models.Model):
    """微信用户模型"""
    openid = models.CharField(max_length=64, unique=True, verbose_name='微信OpenID')
    nickname = models.CharField(max_length=64, blank=True, null=True, verbose_name='昵称')
    avatar = models.URLField(max_length=256, blank=True, null=True, verbose_name='头像')
    gender = models.IntegerField(default=0, verbose_name='性别')  # 0: 未知, 1: 男, 2: 女
    country = models.CharField(max_length=64, blank=True, null=True, verbose_name='国家')
    province = models.CharField(max_length=64, blank=True, null=True, verbose_name='省份')
    city = models.CharField(max_length=64, blank=True, null=True, verbose_name='城市')
    token = models.CharField(max_length=64, blank=True, null=True, verbose_name='登录Token')
    token_expires_at = models.DateTimeField(blank=True, null=True, verbose_name='Token过期时间')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '微信用户'
        verbose_name_plural = verbose_name
        db_table = 'wechat_user'

    def __str__(self):
        return f"{self.nickname or '未知用户'} ({self.openid})"

    def is_token_valid(self):
        """检查token是否有效"""
        if not self.token or not self.token_expires_at:
            return False
        return timezone.now() < self.token_expires_at